using System;
using System.Collections;
using System.Collections.Generic;
using FrameWork;
using UnityEngine;

//
[System.Serializable]
public class Sound
{
    public string SoundName;
    public AudioClip SoundClip;
}
/// <summary>
/// 在这管理 BGM 和 SFX
/// </summary>
public class AudioManager : MonoBehaviour
{
    [Header("背景音乐播放组件")]
    [SerializeField] private AudioSource audioSourceBGM;
    
    [Header("BGM")]
    public Sound[] soundsBGM;
    [Header("SFX")]
    public Sound[] soundsSFX;



    #region Life cycle function

    private void Start()
    {
        AudioData.Instance.AddListener(OnUpdateVolumeBGMInfo);
        
        // 事件注册，用于播放 BGM 和 SFX
        EventSystem.Instance.AddListener<string>(EventName.EVENT_AUDIO_BGM_PLAY, PlayBGM);
        EventSystem.Instance.AddListener<string>(EventName.EVENT_AUDIO_SFX_PLAY, PlaySFX);
    }
    
    //
    private void OnDisable()
    {
        AudioData.Instance.RemoveListener(OnUpdateVolumeBGMInfo);
        
        // 移除事件
        EventSystem.Instance.RemoveListener<string>(EventName.EVENT_AUDIO_BGM_PLAY, PlayBGM);
        EventSystem.Instance.RemoveListener<string>(EventName.EVENT_AUDIO_SFX_PLAY, PlaySFX);
    }

    #endregion

    
    //

    #region Music Control

    private void PlayBGM(string soundName)
    {
        Sound s = Array.Find(soundsBGM, sound => sound.SoundName == soundName);

        if (s == null)
        {
            Debug.LogError("找不到音乐" + soundName);
        }
        else
        {
            audioSourceBGM.clip = s.SoundClip;
            audioSourceBGM.volume = AudioData.Instance.GetAudioVolumeBGM;
            audioSourceBGM.Play();
        }
    }
    
    //
    private void PlaySFX(string soundName)
    {
        Sound s = Array.Find(soundsSFX, sound => sound.SoundName == soundName);

        if (s == null)
        {
            Debug.LogError("找不到音乐" + soundName);
        }
        else
        {
            GameObject obj = ObjectPool.Instance.Spawn("AudioSFX");
            if (obj == null)
            {
                Debug.LogError("音效播放预制体加载失败");
            }
            
            AudioSource audioSource = obj.GetComponent<AudioSource>();
            if (audioSource == null)
            {
                Debug.LogError("音效组件不存在");
            }
            
            audioSource.clip = s.SoundClip;
            audioSource.volume = AudioData.Instance.GetAudioVolumeBGM;
            audioSource.Play();
        }
    }

    #endregion

    #region Event Update

    //
    private void OnUpdateVolumeBGMInfo(float volumeBGM)
    {
        audioSourceBGM.volume = volumeBGM;
    }

    #endregion
}
